#include "wxSceneGraphicsContext.h"
#include "wxSceneCanvas.h"
// ===========================================================================
// wxSceneCanvas::GraphicsContext implementation
// ===========================================================================

unsigned int wxSceneGraphicsContext::sGLContextRefs(0);

wxSceneGraphicsContext::wxSceneGraphicsContext(wxSceneCanvas* canvas)
{
	pSceneCanvas = canvas;
	pGLContext = new wxGLContext(pSceneCanvas);
	mGLContextID = sGLContextRefs++;
}

wxSceneGraphicsContext::~wxSceneGraphicsContext()
{
	assert(pGLContext);
	delete pGLContext;
}

void wxSceneGraphicsContext::detachFromCanvas()
{
	pSceneCanvas = NULL;
}

wxGLContext* wxSceneGraphicsContext::getWxContext()
{
	return pGLContext;
}

unsigned int wxSceneGraphicsContext::getGlContext()
{
	return mGLContextID;
}

bool wxSceneGraphicsContext::valid() const 
{
	return pSceneCanvas ? pSceneCanvas->IsShownOnScreen() : false;
}

bool wxSceneGraphicsContext::realizeImplementation()
{
	if (pSceneCanvas)
	{
		pSceneCanvas->Show(true);
		return true;
	}else{
		return false;
	}
}

bool wxSceneGraphicsContext::isRealizedImplementation() const
{
	return pSceneCanvas ? pSceneCanvas->IsShownOnScreen() : false;
}

void wxSceneGraphicsContext::closeImplementation()
{
	osg::notify(osg::WARN) << "wxSceneCanvas::GraphicsContext::closeImplementation() : unimplemented" << std::endl;
}


bool wxSceneGraphicsContext::makeCurrentImplementation()
{
	if (pSceneCanvas)
	{
		if (!pSceneCanvas->isRenderingActive())
			return false;
#ifdef HAS_OSG_WXGL_ADDONS
		return pSceneCanvas->SetCurrent(*_context);
#else
#ifdef _WIN32
		SetLastError(0); // utterly clumsy (part I)
		pSceneCanvas->SetCurrent(*pGLContext);
		return GetLastError() == 0; // utterly clumsy (part II)
#else
		pSceneCanvas->SetCurrent(*_context);
		return true;				// even worse
#endif //_WIN32
#endif //HAS_OSG_WXGL_ADDONS
	}
	else
		return false;
}

bool wxSceneGraphicsContext::makeContextCurrentImplementation(osg::GraphicsContext*)
{
	osg::notify(osg::WARN) << "wxSceneCanvas::GraphicsContext::makeContextCurrentImplementation() : unimplemented" << std::endl;
	return false;
}

bool wxSceneGraphicsContext::releaseContextImplementation()
{
	//	osg::notify(osg::WARN) << "wxSceneCanvas::GraphicsContext::releaseContextImplementation() : unimplemented" << std::endl;
	return false; // The OSG does not check for the return value anyway
}

void wxSceneGraphicsContext::bindPBufferToTextureImplementation(GLenum buffer)
{
	osg::notify(osg::WARN) << "wxSceneCanvas::GraphicsContext::bindPBufferToTextureImplementation() : unimplemented" << std::endl;
}

void wxSceneGraphicsContext::swapBuffersImplementation()
{
	if (pSceneCanvas)
		pSceneCanvas->SwapBuffers();
}
